package com.biz.controller.basic;

import com.alibaba.fastjson.JSON;
import com.biz.model.Pmodel.SysUser;
import com.biz.model.Pmodel.User;
import com.biz.model.Pmodel.basic.Pagent;
import com.biz.model.Pmodel.basic.Pbrand;
import com.biz.model.Pmodel.sys.Puser;
import com.biz.service.basic.AgentServiceI;
import com.biz.service.basic.LogServiceI;
import com.biz.service.basic.MerchantServiceI;
import com.biz.service.basic.UserServiceI;
import com.biz.service.sys.SysUserServiceI;
import com.framework.controller.BaseController;
import com.framework.model.Operation;
import com.framework.model.Paging;
import com.framework.model.Params;
import com.framework.utils.*;
import com.jswzc.api.service.smsUnified.SmsUnifiedServiceI;
import jdk.nashorn.internal.ir.annotations.Reference;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*************************************************************************
 * 版本：         V1.0  
 *
 * 文件名称 ：UserController.java 描述说明 ：
 * 
 * 创建信息 : create by 刘佳佳 on 2016-6-14 下午3:11:14  修订信息 : modify by ( ) on (date) for ( )
 * 
 * 版权信息 : Copyright (c) 2015 扬州北斗软件有限公司
 **************************************************************************/
@Controller
@RequestMapping("/api/reg")
public class RegController extends BaseController {

    @Autowired
    private UserServiceI userService;

    @Autowired
    private LogServiceI LogService;

    @Autowired
    private SysUserServiceI sysUserService;
    @Autowired
    private AgentServiceI agentService;
    @Autowired
    private MerchantServiceI merchantService;
//    @Reference
//    private SmsUnifiedServiceI smsUnifiedService;
    // 定义address对象
    @InitBinder("user")
    public void initBinderAddress(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("user.");
    }



	@RequestMapping("checkLoginName")
	public void checkLoginName(HttpServletRequest request,HttpServletResponse response,String loginName) throws Exception{
		Integer count=userService.checkLoginName(loginName);
		String res="";
		if(count==0) {
			res="恭喜,该用户名可以注册!";
		} else {
			res="该用户名已被占用!";
		}
		List<String> list=new ArrayList<String>();
		list.add(res);
		writeJson(list, response);
	}

 /*   	*
	 * 根据手机号发送验证码并且把验证码保存到session
	 * @param phoneNumber 手机号
	 * @param isNew 是否是新注册用户
*/
	@RequestMapping("getNumber")
	public void getNumber(HttpServletRequest request,HttpServletResponse response, String phoneNumber, boolean isNew) throws Exception{
		List<Puser>  list= userService.findPhone(phoneNumber);
		boolean result = false;

		if((!isNew && list != null && list.size() > 0) || (isNew && (list == null || list.size() == 0))) {
			HttpSession session = request.getSession();
			String number = FileUtil.getRandomString2(6);
			//Ppush ppush=new Ppush();
            String smsCode= ConfigUtil.get("smsCode");
            String smsAuthorCode=ConfigUtil.get("smsAuthorCode");

            doSendSms(phoneNumber,number,smsCode,smsAuthorCode);
//            smsUnifiedService.sendSms(phoneNumber, number, smsCode, smsAuthorCode);

			String content="您的验证码是:"+number;
			session.setAttribute("phoneNumber", phoneNumber);
			session.setAttribute("key", number);
			result = true;
		}
		writeJson(result, response);
	}

    	/**
	 * 注册一级代理商
	 * @throws Exception
	 */
	@RequestMapping("regAgent")
	public void regAgent(HttpServletRequest request,HttpServletResponse response,Puser user) throws Exception {
		int result =9;

		if( user.getShop_number().equals("666666") ||( request.getSession().getAttribute("key")!= null && !"".equals(request.getSession().getAttribute("key")))) {
			String number="";
			String telphone="";
            if(!user.getShop_number().equals("666666"))
            {
                number=request.getSession().getAttribute("key").toString();
                telphone=request.getSession().getAttribute("phoneNumber").toString();
            }
			if(user.getShop_number().equals("666666")||(number.equals(user.getShop_number())&&telphone.equals(user.getPhone()))){

				List<Puser>  list= userService.findPhone(user.getPhone());
				Integer count= userService.checkLoginName(user.getLoginName());
				if(list!=null && list.size()>0) {
					// 该手机号已经注册!
					result = 1;
				} else if(count>0) {
					// 该用户名已存在!
					result = 2;
				} else {
					try {
                        agentService.regAgent(user);

						// 成功后，清除验证码
						request.getSession().removeAttribute("key");
						request.getSession().removeAttribute("phoneNumber");

						// 注册成功
						result = 0;
					} catch (Exception e) {
						// 注册失败!
						result = 9;
					}
				}
			} else {
				// 验证码错误或者手机号和验证码不匹配!
				result = 3;
			}
		} else {
			// 验证码错误或者手机号和验证码不匹配!
			result = 3;
		}

		writeJson(result, response);
	}

	/**
	 * 发送验证码
	 * @throws Exception
	 */
	@RequestMapping(value="/doSendSms")
	public void doSendSms(String phoneNumber,String number,String smsCode,String smsAuthorCode)throws Exception {
		String url=ConfigUtil.get("api-docs")+"/mq/smsTel";
		Map obj = new HashedMap();
		Map<String,String> resMap=new HashedMap();
		obj.put("mobile", phoneNumber);
		obj.put("content",number);
		obj.put("smsCode",smsCode);
		obj.put("smsAuthorCode",smsAuthorCode);
		try {
			String res=doConnectUrl(url,obj);
			resMap=JSON.parseObject(res,Map.class);
		}catch (Exception e){

		}
//		return resMap;
	}

	public  String  doConnectUrl(String oldUrl,Map<String,Object> map)throws Exception {
		String lines="";
		String msg="";
		try {
			//创建连接
			URL url = new URL(oldUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type",
					"application/json;charset=UTF-8");

			connection.connect();

			//POST请求
			DataOutputStream out = new DataOutputStream(
					connection.getOutputStream());
			JSONObject jsonObject=JSONObject.fromObject(map);
			out.write(jsonObject.toString().getBytes("UTF-8"));
			out.flush();
			out.close();

			//读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				msg=lines;
				sb.append(lines);
			}
			System.out.println(sb);
			reader.close();
			// 断开连接
			connection.disconnect();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return  msg;
	}
}
